package com.st.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.mysql.cj.util.StringUtils;
import com.st.common.constant.ProductConstant;
import com.st.mall.product.dao.AttrAttrgroupRelationDao;
import com.st.mall.product.dao.AttrGroupDao;
import com.st.mall.product.dao.CategoryDao;
import com.st.mall.product.entity.*;
import com.st.mall.product.service.AttrGroupService;
import com.st.mall.product.service.ProductAttrValueService;
import com.st.mall.product.vo.AttrResVo;
import com.st.mall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.st.common.utils.PageUtils;
import com.st.common.utils.Query;

import com.st.mall.product.dao.AttrDao;
import com.st.mall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao aardao;
    @Autowired
    private AttrGroupDao agdao;
    @Autowired
    private CategoryDao cateDao;
    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long cateLogId, String type) {
        IPage<AttrEntity> page;
        String key = (String) params.get("key");
        LambdaQueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().lambda()
                .eq(AttrEntity::getAttrType,"base"
                        .equals(type)?ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        //如果key不为空，添加模糊查询条件
        if (!StringUtils.isNullOrEmpty(key)) {
            wrapper.and(getObj -> {
                getObj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }
        //分类id不为0，进行拼上cateLogId
        if (!cateLogId.equals(0L)) {
            wrapper.eq(AttrEntity::getCatelogId, cateLogId);
        }
        page = this.page(new Query<AttrEntity>().getPage(params),
                wrapper
        );
        //封装上响应字段
        List<AttrEntity> records = page.getRecords();
        List<AttrResVo> resVoList = records.stream().map((attrEntity) -> {
            AttrResVo attrResVo = new AttrResVo();
            BeanUtils.copyProperties(attrEntity, attrResVo);
            //设置分类名和分组名
            AttrAttrgroupRelationEntity attrId = aardao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", attrEntity.getAttrId()));
            if (attrId != null) {
                AttrGroupEntity attrGroup = agdao.selectById(attrId.getAttrGroupId());
                attrResVo.setGroupName(attrGroup.getAttrGroupName());
            }
            CategoryEntity categoryEntity = cateDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResVo.setCatelogName(categoryEntity.getName());
            }
            return attrResVo;
        }).collect(Collectors.toList());
        //更新PageUtils结果集为resVoList
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(resVoList);
        return pageUtils;
    }

    @Override
    public AttrVo getDetails(Long attrId) {
        AttrResVo attrResVo = new AttrResVo();
        AttrEntity byId = this.getById(attrId);
        if(byId!=null){
            BeanUtils.copyProperties(byId,attrResVo);
            if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()==byId.getValueType()) {
                //添加完整分类id路径和分类名
                Long[] ctLogPath = attrGroupService.getCtLogPath(byId.getCatelogId());
                attrResVo.setCatelogPath(ctLogPath);
                CategoryEntity categoryEntity = cateDao.selectById(byId.getCatelogId());
                if (categoryEntity != null) {
                    attrResVo.setCatelogName(categoryEntity.getName());
                }
            }
            //添加完整分组id和分组名
            AttrAttrgroupRelationEntity relation = aardao
                    .selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id", byId.getAttrId()));
            if(relation!=null&&relation.getAttrGroupId()!=null){
                attrResVo.setAttrGroupId(relation.getAttrGroupId());
                AttrGroupEntity attrGroup = agdao.selectById(relation.getAttrGroupId());
                if(attrGroup!=null){
                    attrResVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }
        }
        return attrResVo;
    }
    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //实体类属性复制
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //维护关系表
        if(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()==attr.getValueType()&&attr.getAttrGroupId()!=null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            aardao.insert(relationEntity);
        }

    }

    @Transactional
    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if(attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            //1、修改分组关联
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = aardao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if(count>0){
                aardao.update(relationEntity,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                        .lambda().eq(AttrAttrgroupRelationEntity::getAttrId,attr.getAttrId()));
            }else{
                aardao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<ProductAttrValueEntity> getForSpu(Long spuI) {
        List<ProductAttrValueEntity> list=productAttrValueService.getAttrBySpuId(spuI);
        return list;
    }

    @Override
    public List<Long> getCouldSearchBy(List<Long> ids) {
        return baseMapper.getSearchable(ids);
    }


}